package com.damai.action.factories;

import java.lang.reflect.Method;
import java.util.List;

import com.citywithincity.reflect.CtClassUtil;
import com.damai.action.ApiAction;
import com.damai.action.IAction;
import com.damai.action.IActionFactory;
import com.damai.action.IParamParser;
import com.damai.action.IParamParserFactory;
import com.damai.action.IRenderFactory;
import com.damai.action.aop.Interceptor;
import com.damai.action.aop.InvokerFactory;
import com.damai.action.aop.impl.InvokerFactoryImpl;
import com.damai.action.meta.ApiMetaDataFactory;
import com.damai.mvc.view.ErrorRender;

import javassist.ClassPool;

abstract class AbsActionFactory implements IActionFactory {

	private IParamParserFactory paramParserFactory;
	private InvokerFactory invokerFactory;
	private IRenderFactory renderFactory;
	private ErrorRender errorRender;
	
	public AbsActionFactory(IParamParserFactory paramParserFactory,
			IRenderFactory renderFactory,
			ErrorRender errorRender){
		invokerFactory = InvokerFactoryImpl.DEFAULT;
		this.paramParserFactory = paramParserFactory;
		this.renderFactory = renderFactory;
		this.errorRender = errorRender;
	}
	


	@Override
	public IAction createAction(ClassPool classPool,  Class<?> controllerClass, Method method, String key, List<Interceptor> interceptors) {
		IParamParser parser = paramParserFactory.createParser( classPool, controllerClass, method);
		
		
		try {
			return new ApiAction(parser, 
					invokerFactory.createInvoker(controllerClass, method,interceptors),
					renderFactory.createRender(controllerClass, method),
					errorRender,
					key,
					/**/
					ApiMetaDataFactory.create(key,controllerClass,method,classPool),
					controllerClass,
					method,
					CtClassUtil.getParams(classPool, controllerClass, method)
					
					);
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}
	
}
